'use strict'

const { ApiController } = require('jax')

class AdminDepartmentController extends ApiController {
  get Model() {
    return this.ctx.model.AdminDepartment
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { query, helper } = ctx
    const { admin } = ctx.state

    const filter = {
      // 所属系统
      systemType: admin.systemType,
    }

    // 模糊查询
    const search = ['departmentName']
    for (let key of search) {
      if (query[key]) filter[key] = new RegExp(helper.toMongoRegex(query[key]), 'i')
    }

    ;['systemType', 'sourceId'].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    // 非管理员系统
    if (admin.systemType != 'admin') {
      filter.sourceId = admin.sourceId
    }
    return {
      filter,
    }
  }

  // 新增前
  async beforeCreate() {
    const { ctx } = this
    const { body } = ctx.request
    const { admin } = ctx.state

    // 所属系统
    body.systemType = admin.systemType
    // 设置角色来源
    body.sourceId = admin.sourceId
  }

  // 格式化
  async formatData(department) {
    const { ctx } = this

    // 关联当前部门的用户数
    department.userNum = await ctx.model.Admin.count({ departmentId: department.departmentId })
  }

  // 删除前
  async beforeDestroy() {
    const { ctx } = this
    const { params } = ctx

    // 判断部门是否绑定了子部门
    const res = await ctx.model.AdminDepartment.find({ parentId: params.id })
    if (res.length != 0) throw '该部门绑定了子部门，不能删除'
  }
}

module.exports = AdminDepartmentController
